#include "wtlpch.h"

#include "resource.h"
#include "DownPropertyDiag.h"
#include "ErrorHandler.h"

CDownPropertyPage::CDownPropertyPage(void) : m_nThread(2), m_pvecLinksData(NULL), m_bIsKeepTask(false)
{
}

CDownPropertyPage::~CDownPropertyPage(void)
{
}

void CDownPropertyPage::OnDataExchangeError(UINT nCtrlID, BOOL bSave)
{

}

void CDownPropertyPage::OnDataValidateError(UINT nCtrlID, BOOL bSave, _XData& data)
{
	//Warning Thread Number
	if(nCtrlID == IDC_DOWNPROP_THREAD)
	{
		CErrorHandler::ShowMessageWithParam(*this, IDS_TA_DOWNPROP_PARAM_ERROR_TITLE, IDS_TA_DOWNPROP_THREAD_ERROR, MB_OK | MB_ICONWARNING, 1, CErrorHandler::TYPE_INT, DOWNPROP_MAX_THREAD);
	}
}

void CDownPropertyPage::RefreshSettings()
{
	//update xml settings
	_ConfigApp.AppSettings.uiDefDownThread = (UINT)m_nThread;
	_ConfigApp.AppSettings.wstrDefSavePath = m_wstrSaveFolder;

	_ConfigApp.AppSettings.bIsStartNow = (m_btnIsStartNow.GetCheck() == BST_CHECKED ? true : false);
}

LRESULT CDownPropertyPage::OnInitDialog(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
{
	//Remove the ? Button and center window
	CPropertySheetWindow prtSheet = GetPropertySheet();
	prtSheet.CenterWindow(prtSheet.GetParent());
	prtSheet.ModifyStyleEx(WS_EX_CONTEXTHELP, 0);

	//Attach Listbox
	m_treeFileList.Attach(GetDlgItem(IDC_DOWNPROP_FILELIST));

	//Attach Editbox
	m_edtThread.Attach(GetDlgItem(IDC_DOWNPROP_THREAD));
	m_edtThread.SetLimitText(DOWNPROP_MAX_THREAD_DIGITALS-1);

	//Attach Spin
	m_spThread.Attach(GetDlgItem(IDC_DOWNPROP_THREAD_PIN));
	m_spThread.SetBuddy(m_edtThread);

	//Attach SavePath
	m_edtSavePath.Attach(GetDlgItem(IDC_EDIT_FOLDER_PATH));

	//Attach Radio
	m_btnIsStartNow.Attach(GetDlgItem(IDC_RADIO_START_NOW));
	m_btnIsKeepTask.Attach(GetDlgItem(IDC_RADIO_KEEP_TASK));

	//Attach Checkbox
	m_chkSaveDefault.Attach(GetDlgItem(IDC_CHECK_KEEP_AS_DEFAULT));

	//Init Download file items
	ATLASSERT(m_pvecLinksData != NULL);
	for(vector<CCURLHelper::PAGE_LINK_ITEM*>::iterator it = m_pvecLinksData->begin(); it != m_pvecLinksData->end(); ++it)
	{
		//Set Tree files
		m_treeFileList.InsertItem((*it)->wstrServerFileName.c_str(), TVI_ROOT, TVI_LAST);
	}

	//Init Controls
	//Down Thread Edit
	m_edtThread.SetWindowTextW(_ConfigApp.AppSettings.uiDefDownThread);

	//Save Path Edit, if not defined, we set it as the user's document folder
	if(_ConfigApp.AppSettings.wstrDefSavePath.length() == 0)
	{
		WCHAR lpwstrDocPath[MAX_PATH] = { 0 };
		HRESULT hr = SHGetFolderPath(NULL, CSIDL_PERSONAL, NULL, SHGFP_TYPE_CURRENT, lpwstrDocPath);

		if(hr == S_OK)
		{
			_ConfigApp.AppSettings.wstrDefSavePath = lpwstrDocPath;
		}
		else
		{
			_ConfigApp.AppSettings.wstrDefSavePath = L"C:\\";
		}
	}
	m_edtSavePath.SetWindowTextW(_ConfigApp.AppSettings.wstrDefSavePath.c_str());
	m_wstrSaveFolder = _ConfigApp.AppSettings.wstrDefSavePath;

	//Task Type Radio
	if(_ConfigApp.AppSettings.bIsStartNow)
	{
		m_btnIsStartNow.SetCheck(BST_CHECKED);
	}
	else
	{
		m_btnIsKeepTask.SetCheck(BST_CHECKED);
	}

	//Set default checkbox
	m_chkSaveDefault.SetCheck(BST_CHECKED);

	return TRUE;
}

LRESULT CDownPropertyPage::OnSpinClick(int nCtrlId, LPNMHDR lpnmhdr, BOOL& bHandled)
{
	LPNMUPDOWN lpUPD = (LPNMUPDOWN)lpnmhdr;

	//Get Edit box current value
	::wmemset(m_pwstrThread, 0, DOWNPROP_MAX_THREAD_DIGITALS);
	m_edtThread.GetLine(0, m_pwstrThread, DOWNPROP_MAX_THREAD_DIGITALS);

	m_nThread = ::_wtoi(m_pwstrThread);

	if(lpUPD->iDelta > 0)
	{
		m_nThread--;
	}
	else
	{
		m_nThread++;
	}

	//Correct the Input
	if(m_nThread < 1) m_nThread = 1;
	if(m_nThread > DOWNPROP_MAX_THREAD) m_nThread = DOWNPROP_MAX_THREAD;

	//Refresh Thread Edit value
	::wmemset(m_pwstrThread, 0, DOWNPROP_MAX_THREAD_DIGITALS);
	::_itow(m_nThread, m_pwstrThread, 10);
	m_edtThread.SetWindowTextW(m_pwstrThread);

	return TRUE;
}

LRESULT CDownPropertyPage::OnDestroy(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
{
	return TRUE;
}

LRESULT CDownPropertyPage::OnJumpToExport(WORD wNotifyCode, WORD wID, HWND hWndCtl, BOOL& bHandled)
{
	CPropertySheetWindow prtSheet = GetPropertySheet();
	prtSheet.SetActivePage(1);

	return TRUE;
}

LRESULT CDownPropertyPage::OnBrowseFolder(WORD wNotifyCode, WORD wID, HWND hWndCtl, BOOL& bHandled)
{
	WCHAR pwstrFile[32] = { 0 };

	//Load Title String
	::LoadStringW(_Module.m_hInst, IDS_TA_DOWNPROP_SELFOLDER, pwstrFile, 32);

	CFolderDialog diagBrowseFolder;
	diagBrowseFolder.m_bi.lpszTitle = pwstrFile;
	diagBrowseFolder.m_bi.ulFlags = BIF_NEWDIALOGSTYLE | BIF_RETURNONLYFSDIRS;
	diagBrowseFolder.SetInitialFolder(m_wstrSaveFolder.c_str(), false);

	//Show the folder select diag
	if(diagBrowseFolder.DoModal(m_hWnd) == IDOK)
	{
		//If User Select a folder, refresh the Path edit and member var
		m_wstrSaveFolder = diagBrowseFolder.GetFolderPath();
		m_edtSavePath.SetWindowTextW(m_wstrSaveFolder.c_str());
	}

	return TRUE;
}

CDownExportLinkPage::CDownExportLinkPage() : m_pvecLinksData(NULL)
{

}

CDownExportLinkPage::~CDownExportLinkPage()
{

}

void CDownExportLinkPage::RefreshSettings()
{
	//Update XML Settings
	_ConfigApp.AppSettings.bIsDefSendFlash = (m_radSendFlash.GetCheck() == BST_CHECKED ? true : false);
	_ConfigApp.AppSettings.bIsDefExpHttp = (m_radExpHttp.GetCheck() == BST_CHECKED ? true : false);
	_ConfigApp.AppSettings.bIsDefEncGB = (m_radEncGB.GetCheck() == BST_CHECKED ? true : false);

	_ConfigApp.AppSettings.wstrListSavePath = m_wstrListPath;
}


LRESULT CDownExportLinkPage::OnInitDialog(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
{
	//Remove the ? Button
	CPropertySheetWindow prtSheet = GetPropertySheet();
	prtSheet.ModifyStyleEx(WS_EX_CONTEXTHELP, 0);

	//Init the Contorls
	m_edtLinks.Attach(GetDlgItem(IDC_EDIT_EXPT_LINKS));
	ATLASSERT(m_pvecLinksData != NULL);
	wstring wstrLinkText;
	for(vector<CCURLHelper::PAGE_LINK_ITEM*>::iterator it = m_pvecLinksData->begin(); it != m_pvecLinksData->end(); ++it)
	{
		//Convert the text with return
		wstrLinkText += (*it)->wstrServerFileName;
		wstrLinkText += L"\r\n";

		WCHAR pwstrURL[_CURL_MAX_URL_LENGTH] = { 0 };
		::MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, (*it)->strDownLink.c_str(), -1, pwstrURL, _CURL_MAX_URL_LENGTH);

		wstrLinkText += pwstrURL;
		wstrLinkText += L"\r\n\r\n";
	}

	m_edtLinks.SetWindowTextW(wstrLinkText.c_str());

	//Attach Controls
	m_radSendFlash.Attach(GetDlgItem(IDC_RADIO_SENDFLASHGET));
	m_radSaveDisk.Attach(GetDlgItem(IDC_RADIO_SAVEDISK));

	m_radExpHttp.Attach(GetDlgItem(IDC_RADIO_EXPHTTP));
	m_radExpFTP.Attach(GetDlgItem(IDC_RADIO_EXPFTP));

	m_radEncGB.Attach(GetDlgItem(IDC_RADIO_ENCGB));
	m_radEncUTF.Attach(GetDlgItem(IDC_RADIO_ENCUTF));

	m_edtListSavePath.Attach(GetDlgItem(IDC_EDIT_LIST_SAVE_PATH));
	m_btnBrowsPath.Attach(GetDlgItem(IDC_BUTTON_BROSE_LIST_PATH));

	m_chkSaveDefault.Attach(GetDlgItem(IDC_CHECK_KEEP_AS_DEFAULT));

	//Init Control Status and notify the window
	//This method won't generate a msg, so we have to post it ourself to fire the precedure
	_ConfigApp.AppSettings.bIsDefSendFlash ? m_radSendFlash.SetCheck(BST_CHECKED) : m_radSaveDisk.SetCheck(BST_CHECKED);
	PostMessageW(WM_COMMAND, MAKELPARAM(IDC_RADIO_SENDFLASHGET, NULL), (LPARAM)m_radSendFlash.m_hWnd);

	//Set Export format radio
	_ConfigApp.AppSettings.bIsDefExpHttp ? m_radExpHttp.SetCheck(BST_CHECKED) : m_radExpFTP.SetCheck(BST_CHECKED);

	//Set Export Encode radio
	_ConfigApp.AppSettings.bIsDefEncGB ? m_radEncGB.SetCheck(BST_CHECKED) : m_radEncUTF.SetCheck(BST_CHECKED);

	//Set checkbox
	m_chkSaveDefault.SetCheck(BST_CHECKED);

	//Set Export Path
	if(_ConfigApp.AppSettings.wstrListSavePath.length() == 0)
	{
		WCHAR lpwstrDocPath[MAX_PATH] = { 0 };
		WCHAR lpwstrDefFileName[16] = { 0 };

		//Load Default Filename, and get User folder
		::LoadStringW(_Module.m_hInst, IDS_TA_DOWNPROP_DEFFILENAME, lpwstrDefFileName, 16);
		HRESULT hr = SHGetFolderPath(NULL, CSIDL_PERSONAL, NULL, SHGFP_TYPE_CURRENT, lpwstrDocPath);

		if(hr == S_OK)
		{
			::PathAppend(lpwstrDocPath, lpwstrDefFileName);
			_ConfigApp.AppSettings.wstrListSavePath = lpwstrDocPath;
		}
		else
		{
			_ConfigApp.AppSettings.wstrListSavePath = L"C:\\";
			_ConfigApp.AppSettings.wstrListSavePath += lpwstrDefFileName;
		}
	}

	m_edtListSavePath.SetWindowTextW(_ConfigApp.AppSettings.wstrListSavePath.c_str());
	m_wstrListPath = _ConfigApp.AppSettings.wstrListSavePath;

	return TRUE;
}

LRESULT CDownExportLinkPage::OnDestroy(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
{
	return TRUE;
}

LRESULT CDownExportLinkPage::OnRadioExportType(WORD wNotifyCode, WORD wID, HWND hWndCtl, BOOL& bHandled)
{
	//If Send to flash get, the downlist options should be disabled
	if(m_radSendFlash.GetCheck() == BST_CHECKED)
	{
		m_radExpHttp.EnableWindow(FALSE);
		m_radExpFTP.EnableWindow(FALSE);

		m_radEncGB.EnableWindow(FALSE);
		m_radEncUTF.EnableWindow(FALSE);

		m_edtListSavePath.EnableWindow(FALSE);
		m_btnBrowsPath.EnableWindow(FALSE);
	}

	//Or if we want to export to list, these options should be open
	if(m_radSaveDisk.GetCheck() == BST_CHECKED)
	{
		m_radExpHttp.EnableWindow(TRUE);
		m_radExpFTP.EnableWindow(TRUE);

		m_radEncGB.EnableWindow(TRUE);
		m_radEncUTF.EnableWindow(TRUE);

		m_edtListSavePath.EnableWindow(TRUE);
		m_btnBrowsPath.EnableWindow(TRUE);
	}

	return FALSE;
}

LRESULT CDownExportLinkPage::OnBrowseListPath(WORD wNotifyCode, WORD wID, HWND hWndCtl, BOOL& bHandled)
{
	//Load String from resource
	WCHAR lpwstrDefExt[8] = { 0 };
	WCHAR lpwstrDefFileName[16] = { 0 };
	WCHAR lpwstrFilter[128] = { 0 };

	::LoadStringW(_Module.m_hInst, IDS_TA_DOWNPROP_DEFEXT, lpwstrDefExt, 8);
	::LoadStringW(_Module.m_hInst, IDS_TA_DOWNPROP_DEFFILENAME, lpwstrDefFileName, 16);
	::LoadStringW(_Module.m_hInst, IDS_TA_DOWNPROP_FILTER, lpwstrFilter, 128);

	//Modify the filter string
	for(WCHAR* pw = lpwstrFilter; *pw != L'\0'; pw++)
	{
		if(*pw == L'#')
		{
			*pw = L'\0';
		}
	}

	//Show Save file Diag
	CFileDialog diagFileSave(FALSE, lpwstrDefExt, lpwstrDefFileName, OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT, lpwstrFilter);

	//Prepare Init Folder
	WCHAR lpwstrInitFolder[MAX_PATH] = { 0 };
	::wcscpy(lpwstrInitFolder, m_wstrListPath.c_str());
	::PathRemoveFileSpec(lpwstrInitFolder);
	diagFileSave.m_ofn.lpstrInitialDir = lpwstrInitFolder;

	if(diagFileSave.DoModal(m_hWnd) == IDOK)
	{
		m_wstrListPath = diagFileSave.m_szFileName;
		m_edtListSavePath.SetWindowTextW(m_wstrListPath.c_str());
	}

	return TRUE;
}


CDownPropertyDiag::CDownPropertyDiag(ATL::_U_STRINGorID pgTitle, UINT uStartPage, HWND hWndParent) : CPropertySheetImpl(pgTitle, uStartPage, hWndParent)
{
	//Init Member Vars
	m_pvecLinksData = NULL;

	//Set NO apply button
	m_psh.dwFlags |= PSH_NOAPPLYNOW;

	//Set the Icon
	m_psh.dwFlags |= PSH_USEICONID;
	m_psh.pszIcon = MAKEINTRESOURCE(IDI_DOWNPROP_HEADER);

	//Add Property pages
	AddPage(m_pageDownProp);
	AddPage(m_pageExpLink);
}

void CDownPropertyDiag::SetLinksData(vector<CCURLHelper::PAGE_LINK_ITEM*>* pvecLinkData)
{
	ATLASSERT(pvecLinkData != NULL);

	//Set the link data
	m_pvecLinksData = pvecLinkData;

	//Set for members
	m_pageDownProp.m_pvecLinksData = m_pvecLinksData;
	m_pageExpLink.m_pvecLinksData = m_pvecLinksData;
}

LRESULT CDownPropertyDiag::OnOK(WORD wNotifyCode, WORD wID, HWND hWndCtl, BOOL& bHandled)
{
	//Check User push Ok on which page
	if(GetActivePage() == m_pageDownProp)
	{
		//Set Current Page
		m_pgCurrent = PAGE_DOWNPROPERTY;

		if(!m_pageDownProp.DoDataExchange(DDX_SAVE))
		{
			//We won't close until user fix their input
			return FALSE;
		}

		//Check if need to save the settings, if so, we update global setting vars
		if(m_pageDownProp.m_chkSaveDefault.GetCheck() == BST_CHECKED)
		{
			m_pageDownProp.RefreshSettings();
		}
	}
	else	//User want to export
	{
		//Set Current Page
		m_pgCurrent = PAGE_EXPORTLINK;

		//Check if need to save the settings, if so, we update global setting vars
		if(m_pageExpLink.m_chkSaveDefault.GetCheck() == BST_CHECKED)
		{
			m_pageExpLink.RefreshSettings();
		}		
	}

	DestroyWindow();
	return TRUE;
}

LRESULT CDownPropertyDiag::OnCancel(WORD wNotifyCode, WORD wID, HWND hWndCtl, BOOL& bHandled)
{
	m_pgCurrent = PAGE_CANCEL;

	DestroyWindow();
	return FALSE;
}